package com.example.qihuibao.module.main

import android.R
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.os.Bundle
import android.view.Display
import android.view.KeyEvent
import android.view.WindowManager
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.example.qihuibao.base.BaseActivity
import com.example.qihuibao.bean.*
import com.example.qihuibao.constant.Config
import com.example.qihuibao.constant.Global
import com.example.qihuibao.dao.*
import com.example.qihuibao.databinding.ActivityMainBinding
import com.example.qihuibao.module.presentation.MyPresentation
import com.example.qihuibao.network.RetrofitManager
import com.example.qihuibao.utils.DES3Util
import com.example.qihuibao.utils.FirUpdateUtil
import com.example.qihuibao.utils.IpUtil
import com.example.qihuibao.utils.LogUtil
import com.example.qihuibao.utils.extension.toast
import com.example.qihuibao.widget.dialog.*
import com.example.qihuibao.widget.view.BScreenLayout
import com.example.qihuibao.widget.view.CScreenLayout
import com.maning.updatelibrary.InstallUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.*
import kotlin.system.exitProcess


class MainActivity : BaseActivity<ActivityMainBinding>(ActivityMainBinding::inflate) {

    private var myPresentation:MyPresentation? = null
    private lateinit var bScreenLayout:BScreenLayout
    private lateinit var cScreenLayout: CScreenLayout
    private lateinit var vm:MainViewModel
    private var uploadOfflineData = true
    private var oneMinCountdown = 3
    private var isInitializingDevice = false
//    private var enableScan = false
    private var isUpdating = false
    private var isUpdatingOther = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Global.devIp = IpUtil.getHostIP()
        Global.devStat = DevStat.STARTUP
        registerReceiver(networkReceiver, IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"))
        vm = ViewModelProvider(this).get(MainViewModel::class.java)
        initView()
        if (Config.deviceInit) {
            parseInitialQRCode()
            updateOtherData()
        }else {
            Global.devStat = DevStat.INIT
            bScreenLayout.showDevInit()
            cScreenLayout.showDevInit()
        }
    }

    override fun onResume() {
        super.onResume()
        getQRCode {
            when (Global.devStat) {
                DevStat.INIT -> initDevice(it)
                DevStat.STANDBY -> authUser(UserIdentify(null, UserIdentify.CodeBean("000001"), null))//todo
                DevStat.CONSUMING -> toast("请稍后")
                else -> {}
            }
        }
        getTimer {
            bScreenLayout.showConnect(isConnectICBC(), isConnectStation(), getConnectList())
            //定时上传离线数据
            if (uploadOfflineData || Calendar.getInstance().get(Calendar.HOUR_OF_DAY) == 14 || Calendar.getInstance().get(Calendar.HOUR_OF_DAY) == 20) {
                uploadOfflineData = false
                uploadOfflineData()
            }
            if (oneMinCountdown > 0) {
                if (--oneMinCountdown == 0) {
                    oneMinCountdown = 60
                    oneMinTask()
                }
            }
//            if (Config.isServerStation && (!Global.networkOk || !isConnectICBC())) {
//                //服务站发出信号通知本地终端切入互联网离线工作模式
//                sendOfflineNotifyToClient()
//            }
        }
        //服务站发送过来的离线通知
        receiveStation {
            when(it) {
                "station offline" -> bScreenLayout.setOffline(true)
                "station online" -> bScreenLayout.setOffline(false)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(networkReceiver)
    }

    private val networkReceiver = object: BroadcastReceiver(){
        override fun onReceive(context: Context, intent: Intent?) {
            val networkInfo = (context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?)?.activeNetworkInfo;
            Global.networkOk = networkInfo != null && networkInfo.isAvailable
            if (Global.networkOk) {
                Global.devIp = IpUtil.getHostIP()
            }
        }
    }

    private fun initView() {
        //动态加载布局
        bScreenLayout = BScreenLayout(this)
        cScreenLayout = CScreenLayout(this)
        if (Global.hasPresentation) {
            initPresentation()
        }
        viewBinding.root.addView(if (Global.isPresentationForBScreen) cScreenLayout else bScreenLayout)
    }

    private fun initPresentation() {
        val display = MyPresentation.getDisplay()
        if (display != null) {
            if (myPresentation != null && myPresentation?.display?.displayId != Display.DEFAULT_DISPLAY) {
                myPresentation?.dismiss()
                myPresentation = null
            }
            if (myPresentation == null ) {
                myPresentation = MyPresentation(this, display, if (Global.isPresentationForBScreen) bScreenLayout else cScreenLayout)
                try {
                    myPresentation?.show()
                }catch (e: WindowManager.InvalidDisplayException) {
                    myPresentation = null
                }
            }
        }
    }

    private fun loadLocalData() {
//        if (Config.deviceInit) {
            lifecycleScope.launch {
                withContext(Dispatchers.IO) {
//                    Global.currentCanteenInfoBean = MyDatabase.db.canteenInfoDao().queryByCanteenId(Config.currentCanteenId)
//                    Global.currentMealInfoBean = MyDatabase.db.mealInfoDao().queryInId(Config.currentCanteenId, Config.currentMealId)
                    Global.totalOrder = MyDatabase.db.orderInfoDao().queryAll()?.size?:0
                    Global.totalUse = MyDatabase.db.useInfoDao().queryAll()?.size?:0
//                    Global.employs = MyDatabase.db.employInfoDao().queryAll()
                    //todo
                }
                showDevData()
                Global.devStat = DevStat.STANDBY
            }
//        }
    }

    fun initDevice(code:String) {
        LogUtil.e("qrcode = $code")
        if (!isInitializingDevice) {
            isInitializingDevice = true
            try {
                val qrcode = DES3Util.DecryptData(code.replace("\n", ""), Config.INITIAL_QRCODE_KEY)
                val content = qrcode.split("|")
                if (content.size == 5) {
                    Config.INITIAL_QRCODE_CONTENT = qrcode
                    parseInitialQRCode()
                    downloadData() {
                        isInitializingDevice = false
                    }
                }else {
                    toast("二维码无效!")
                    isInitializingDevice = false
                }
            }catch (e:Exception) {
                toast("二维码无效!")
                isInitializingDevice = false
            }
        }
    }

    private fun parseInitialQRCode() {
        val list = Config.INITIAL_QRCODE_CONTENT.split("|")
        if (list.size == 5) {
            repeat(list.size) {
                when(it) {
                    0 -> Global.serverUrl = "http://${list[it]}"
                    1 -> Global.CorpID = list[it]
                    2 -> Global.canteenId = list[it]
                    3 -> Global.CorpName = list[it]
                    4 -> Global.CorpKey = list[it]
                }
            }
            RetrofitManager.getInstance().resetRetrofit()
        }
    }

    private fun downloadData(done:(success:Boolean)->Unit) {
        MultiDownloadDialog(0) {
            if (it) {
                chooseCanteen()
            }else {
                toast("下载失败")
            }
            done.invoke(it)
        }.show(supportFragmentManager, "download")
    }

    fun resetDevice() {
        //todo 恢复出厂设置
        lifecycleScope.launch {
            withContext(Dispatchers.IO) {
                Config.deviceInit = false
                Config.INITIAL_QRCODE_CONTENT = ""
//                Config.enterpriseSecretKey = ""
                Config.currentCanteenId = ""
//                if (File("${FirUpdateUtil.apkDir}111").exists()) {
//                    File("${FirUpdateUtil.apkDir}111").delete()
//                }
                MyDatabase.db.enterpriseInfoDao().deleteAll()
                MyDatabase.db.canteenInfoDao().deleteAll()
                MyDatabase.db.mealInfoDao().deleteAll()
                MyDatabase.db.departmentInfoDao().deleteAll()
                MyDatabase.db.employInfoDao().deleteAll()
                MyDatabase.db.feesInfoDao().deleteAll()
                MyDatabase.db.faceFileInfoDao().deleteAll()
                MyDatabase.db.orderInfoDao().deleteAll()
                MyDatabase.db.payInfoDao().deleteAll()
                MyDatabase.db.useInfoDao().deleteAll()
                MyDatabase.db.dealDao().deleteAll()
                MyDatabase.db.etDealDao().deleteAll()
            }
            toast("已恢复出厂设置")
            //initview
            bScreenLayout.showDevInit()
            cScreenLayout.showDevInit()
        }
    }

    private var userIdentify:UserIdentify? = null
    private var employ:RspQueryEmployInfoBean.Employ? = null
    private var order:RspQueryOrderInfoBean.Order? = null

    //取餐核销/消费
    fun authUser(userIdentify:UserIdentify) {
        if (Global.pageId != 1) return
        if (userIdentify.faceBean == null && userIdentify.codeBean == null && userIdentify.zhangMoBean == null) {
            toast("识别错误，请重试")
            cScreenLayout.toast("识别错误，请重试")
            return
        }
        this.userIdentify = userIdentify
        if (userIdentify.faceBean != null) {
            queryEmployInfo(userIdentify)
        }else if (userIdentify.codeBean != null) {
            //二维码视为电子餐票
            employ = RspQueryEmployInfoBean.Employ()
            employ?.EmpID = userIdentify.codeBean!!.codeId!!
            employ?.EmpName = "cww"
            queryEmployOrder(employ!!)
        }else {
            //todo
        }
    }

    private fun queryEmployInfo(userIdentify:UserIdentify) {
        //用户输入只有刷脸、扫码或其它，工行并未提供刷脸扫码接口获取用户信息，只能在本地查找用户信息
        lifecycleScope.launch {
            Global.devStat = DevStat.CONSUMING
            showLoading(true, "请稍后")//显示dialog时扫码盒不会不响应(dialog没处理扫码)
            cScreenLayout.showLoading(true, "请稍后")
            //find employ
//            var employ:RspQueryEmployInfoBean.Employ? = null
            withContext(Dispatchers.IO) {
                employ = MyDatabase.db.employInfoDao().queryInEmpID(userIdentify.codeBean!!.codeId!!)
            }
            if (employ == null) {
                showLoading(false)
                toast("找不到人员信息")
                cScreenLayout.showResult("找不到人员信息")
                Global.devStat = DevStat.STANDBY
            }else {
                bScreenLayout.getHomeLayout()?.showEmployInfo(employ)
                cScreenLayout.showEmployInfo(employ)
                queryEmployOrder(employ!!)
            }
        }
    }

    //查找用户订餐明细
    private fun queryEmployOrder(employ:RspQueryEmployInfoBean.Employ) {
        val reqBean = ReqQueryOrderInfoBean(
            CantID = "${Global.currentCanteenInfoBean?.CantID}",	//	餐厅ID
            MealDateBegin = Global.dateFormat.format(Date()),	//	订餐日期开始yyyymmdd
            MealDateEnd = Global.dateFormat.format(Date()),	//	订餐日期结束yyyymmdd
            EmpID = employ.EmpID,	//		员工编号，不填则查询全部,电子餐票订餐记录为电子餐票ID
            EmpName = employ.EmpName,	//		员工姓名，不填则查询全部,电子餐票订餐记录为电子餐票名称
            Status = "0",	//	状态:0 全部,1 已订餐未用餐,2 已用餐,3 统计模式取餐,4 退餐,5部分取餐,6退餐申请待批复,7停餐,8停餐撤消
            EmpType = employ.EmpType,	//		员工类型，不填则查询全部,电子餐票订餐记录为电子类型ID
            DepID1 = employ.DepID1,	//		一级部门ID，不填则查询全部
            DepID2 = employ.DepID2,	//		二级部门ID，不填则查询全部
            OrderType = "0",	//		类型:0全部,1订餐,2现场取餐,3团餐,4停餐,如不送，则默认为1
        )
        vm.queryOrderInfo(reqBean).observe(this@MainActivity) {
            if (it.RetCode == "0") {//todo -1 for test
                if (!it.OrderList.isNullOrEmpty()) {
                    showLoading(false)
                    cScreenLayout.showResult("等待核销")
                    bScreenLayout.getHomeLayout()?.showEmployOrder(it.OrderList!![0])
                    cScreenLayout.showEmployOrder(it.OrderList!![0])
                    //todo
                    return@observe
                }
            }
            //查找本地
            lifecycleScope.launch {
//                var bean : RspQueryOrderInfoBean.Order? = null
                withContext(Dispatchers.IO) {
                    order = MyDatabase.db.orderInfoDao().queryInEmploy(
                        Config.currentCanteenId,
                        employ.EmpID,
                        "20231215",
                        Config.currentMealId)
                }
                if (order != null) {
                    bScreenLayout.getHomeLayout()?.showEmployOrder(order)
                    cScreenLayout.showEmployOrder(order)
                }
                showLoading(false)
                cScreenLayout.showResult("等待核销")
            }
        }
    }

    //取餐核销
    fun writeOff() {
        if (employ == null || order == null) {
            toast("请重新刷脸/扫码")
            return
        }
        if (userIdentify?.faceBean != null) {
            val reqBean = ReqUseConsumeBean(
                listOf(ReqUseConsumeBean.Use(
                    CantID = Config.currentCanteenId,	//	餐厅ID
                    EmpID = "${employ?.EmpID}",	//	员工编号
                    EmpName = "${employ?.EmpName}",	//	员工姓名
                    TranID = "",	//	交易流水号 唯一
                    UpTime = Global.dateTimeFormat.format(Date()),	//	上传时间：yyyymmddhh24miss
                    UpUser = "",	//		上传用户
                    UpType = "0",	//	上传性质：0在线，1脱机，2 补卡，3 修改4 删除
                    UseType = "1",	//	类别：1订餐核销，3 现场取餐，4 现场消费，5 小卖部
                    MealDate = Global.dateTimeFormat.format(Date()),	//	用餐/消费日期yyyymmdd
                    MealID = Config.currentMealId,	//		餐别 01-05，订餐核销/现场取餐必送
                    MealSetID = "order?.MealSetID}",	//		套餐 01-99，订餐核销/现场取餐必送，点餐固定为0
                    FeeID = "${order?.FeeID}",	//		收费标准ID，现场取餐必送
                    Count = order?.Count?:0,	//		取餐份数，订餐核销/现场取餐必送
                    TotalAmt = order?.TotalAmt?:0,	//		总金额（原价）以分为单位，现场取餐可送，如不送，取Amount值
                    DiscountAmt = order?.DiscountAmt?:0,	//		优惠金额 以分为单位，现场取餐可送，如不送，按0处理
                    Amount = order?.Amount?:0,		//	现场消费金额（分），现场取餐/现场消费/小卖部必送
                    Amount1 = order?.Amount1?:0,		//	主账户消费金额（分），对账标准为外部系统可送，不送则按Amount值处理
                    Amount2 = order?.Amount2?:0,		//	补贴账户消费金额（分），对账标准为外部系统，不送则按0处理
                    Balance = 0,		//	最新余额，对账标准为外部系统可送
                    Balance1 = 0,	//		主账户余额，对账标准为外部系统时可送，如不送，而Balance有值，则取Balance值
                    Balance2 = 0,	//		补贴账户余额，对账标准为外部系统时可送,不送则按0处理
                    Remark = "",	//		备注
                    DishList = "${order?.DishList}",	//		菜品列表，格式为:，菜品类型ID1^^菜品1ID^^份数||菜品类型ID2^^菜品2ID^^份数||...，如：001^^00001^^1||002^^00002^^3||，点餐模式现场取餐必送
                    DishCount = 0,		//	菜品数量，如上述例子为2，点餐模式现场取餐必送
                ))
            )
            vm.useConsume(reqBean).observe(this@MainActivity) {useRsp ->
                employ = null
                order = null
                if (useRsp.RetCode == "0" && !useRsp.DealList.isNullOrEmpty()) {
                    for (item in useRsp.DealList) {
                        if (item.DealCode == "0") {
                            toast("取餐/消费 成功")
                            cScreenLayout.showResult("取餐/消费 成功")
                        }else {
                            toast("${item.DealMsg}")
                            cScreenLayout.showResult("${item.DealMsg}")
                        }
                    }
                }else {
                    toast("失败，${useRsp.RetMsg}")
                    cScreenLayout.showResult("失败，${useRsp.RetMsg}")
                }
            }
        }else if (userIdentify?.codeBean != null) {
            val reqBean = ReqETTicketUseConsumeBean(listOf(ReqETTicketUseConsumeBean.Use(
                CantID = Config.currentCanteenId,	//	餐厅ID
                ETicketID = "${employ?.EmpID}",	//	电子餐票ID
                ETicketName = "",	//	电子餐票名称
                ETicketTypeID = "",	//	电子餐票类型ID，91-99
                ChargeType = "",	//	计费标准:1余额 2餐次
                TranID = "",	//	交易流水号 唯一
                TranTime = "",	//	交易时间(实际消费时间):yyyymmddhh24miss
                UpTime = "",	//	上传时间:yyyymmddhh24miss
                UpUser = "",	//		上传用户 (//todo 非必填)
                UpType = "",	//	上传性质 :0在线,1脱机
                UseType = "",	//	类别 :1订餐核销,3 现场取餐
                )))
            vm.etTicketUseConsume(reqBean).observe(this@MainActivity) {useRsp ->
                employ = null
                order = null
                if (useRsp.RetCode == "0" && !useRsp.DealList.isNullOrEmpty()) {
                    for (item in useRsp.DealList) {
                        if (item.DealCode == "0") {
                            toast("取餐/消费 成功")
                            cScreenLayout.showResult("取餐/消费 成功")
                        }else {
                            toast("${item.DealMsg}")
                            cScreenLayout.showResult("${item.DealMsg}")
                        }
                    }
                }else {
                    toast("失败，${useRsp.RetMsg}")
                    cScreenLayout.showResult("失败，${useRsp.RetMsg}")
                }
            }
        }
    }

    //无需订餐的现场取餐
    fun sceneMeal() {
        SceneMealDialog(){ok, mealset, fee ->
            if (ok) {
                SceneMealPayDialog("0.01"){
                    cScreenLayout.showResult("请支付￥$it 元")
                }.show(supportFragmentManager, "")
            }
        }.show(supportFragmentManager, "")
    }


//    private fun progressAuthResult(employ: RspQueryEmployInfoBean.Employ?, done:(success:Boolean, message:String)->Unit) {
//        if (employ != null) {
//            if (false) {//todo 无需订餐的
//                //按照现场取餐规则执行，需按人员类型、份数等餐标规则计算、回显扣收金额
//                done(false, "无需订餐")
//            }else {//todo 需要订餐的
//                //回显当前人员订餐情况，在完成订餐核销后，现场取餐情况受现场取餐规则、线上订餐+现场取餐规则、餐厅配餐参数等规则控制
//                lifecycleScope.launch {
//                    var order:RspQueryOrderInfoBean.Order? = null
//                    withContext(Dispatchers.IO) {
//                        order = MyDatabase.db.orderInfoDao().queryInEmploy(employ.EmpID)
//                    }
//                    bScreenLayout.getHomeLayout()?.showOrder(order)
//                    cScreenLayout.showOrder(order)
//                    done(order != null, "")
//                }
//            }
//            //对于现场取餐，系统自动计算应收金额，现场客服可手工输入调整收费金额
//            //对于未订餐人员服务的时间。未在服务时间内，应予报错
//            writeOff()
//        }else {
//            done(false, "找不到此员工")
//        }
//    }

    //订餐核销
//    private fun writeOff() {
//        //todo
//        //根据餐厅参数，支持自动、客服确认、客户确认、客服-客户确认等几种模式，对于开通客服确认的，需支持手工修改输入金额的功能。
//        uploadWriteOffRecord()
//    }

    private fun uploadWriteOffRecord() {
        //todo 将消费明细上送工行服务器，服务器完成核销或账务处理，可获得正常状态
    }

    fun uploadOfflineData() {
    }

    //差错反交易
    private fun counterTrading() {
        //todo
//        1、订餐已取餐，能正常反交易，恢复订餐未取餐状态；
//        2、现场已取餐并扣费，能正常冲正；冲正形成一笔和原交易相同但方向相反的流水，不删除原交易；
//        3、仅支持当天交易冲正。
//        4、仅支持按照流水号对原交易实现整笔冲正，不支持部分冲正和调整。
    }

    fun getMainViewModel() :MainViewModel {
        return vm
    }

    private fun oneMinTask() {
        checkAppNewVersion()
    }

    private fun checkAppNewVersion() {
        FirUpdateUtil.checkNewVersion {
            if (it.hasNewVersion) {
//                if (File("${FirUpdateUtil.apkDir}${it.version}.apk").exists()) {
//                    InstallUtils.installAPK(this@MainActivity, "${FirUpdateUtil.apkDir}${it.version}.apk", null)
//                }else {
                    InstallUtils.with(this)
                        .setApkUrl("${it.apkUrl}")
                        .setApkPath("${FirUpdateUtil.apkDir}${it.version}.apk")
                        .setCallBack(object: InstallUtils.DownloadCallBack{
                            override fun onStart() {}

                            override fun onComplete(path: String?) {
                                InstallUtils.installAPK(this@MainActivity, path, null)
                            }

                            override fun onLoading(total: Long, current: Long) {}

                            override fun onFail(e: Exception?) {}

                            override fun cancle() {}
                        })
                        .startDownload()
//                }
            }
        }
    }

    private fun showDevData() {
//        if (Global.rspQueryCanteenInfoBean != null) {
            bScreenLayout.getHomeLayout()?.showCanteen()
//        }
        cScreenLayout.showCanteenInfo(Global.currentCanteenInfoBean)
        cScreenLayout.showMealInfo(Global.currentMealInfoBean)
        cScreenLayout.showResult(cScreenLayout.getUseMode())
    }

    fun reInitDevice() {
//        enableScan = true
        Global.devStat = DevStat.INIT
        bScreenLayout.showDevInit()
        cScreenLayout.showDevInit()
    }

    fun exitInitDevice() {
//        enableScan = false
        Global.devStat = DevStat.STANDBY
        bScreenLayout.getHomeLayout()?.showCanteen()
    }

    //获取所有数据
    fun updateData() {
        if (!isUpdating) {
            isUpdating = true
            downloadData() {
                toast("更新${if (it) "成功" else "失败"}")
                isUpdating = false
            }
        }
    }

    //更新人员、余额、订餐数据等资料
    fun updateOtherData() {
        if (!isUpdatingOther) {
            isUpdatingOther = true
            MultiDownloadDialog(1) {
                toast("信息更新${if (it) "成功" else "失败"}")
                loadLocalData()
                isUpdatingOther = false
            }.show(supportFragmentManager, "updateOtherData")
        }
    }

    //选择餐厅
    fun chooseCanteen() {
        lifecycleScope.launch {
            var list:List<RspQueryCanteenInfoBean>? = null
            withContext(Dispatchers.IO) {
                list = MyDatabase.db.canteenInfoDao().queryAll()
            }
            if (!list.isNullOrEmpty()) {
//                Config.deviceInit = true
                if (list!!.size == 1) {
                    //选择唯一餐厅
                    Config.currentCanteenId = list!![0].CantID
                    Global.currentCanteenInfoBean = list!![0]
//                        loadLocalData()
                    chooseMeal()
                }else {
                    CanteenSelectDialog(list) {
//                            loadLocalData()
                        Config.currentCanteenId = list!![it].CantID
                        Global.currentCanteenInfoBean = list!![it]
                        chooseMeal()
                    }.show(supportFragmentManager, "choose")//餐厅选择
                }
            }else {
                toast("没有餐厅信息")
            }
        }
    }

    //选择餐别（按实际时间自动选择？）
    fun chooseMeal() {
        lifecycleScope.launch {
            var list:List<RspQueryMealInfoBean>? = null
            withContext(Dispatchers.IO) {
                list = MyDatabase.db.mealInfoDao().queryInCantID(Config.currentCanteenId)
            }
            if (!list.isNullOrEmpty()) {
                if (list!!.size == 1) {
                    //选择唯一餐别
                    Config.currentMealId = list!![0].MealID
                    Global.currentMealInfoBean = list!![0]
//                    chooseMealSet(list!![0])
                    Config.deviceInit = true
                    loadLocalData()
                }else {
                    MealSelectDialog(list!!) {
                        Config.currentMealId = list!![it].MealID
                        Global.currentMealInfoBean = list!![it]
//                        chooseMealSet(list!![0])
                        Config.deviceInit = true
                        loadLocalData()
                    }.show(supportFragmentManager, "choose")//餐别选择
                }
            }else {
                toast("没有餐别信息")
            }
        }
    }

    //选择套餐（直接显示？+收费标准？）
//    private fun chooseMealSet(meal:RspQueryMealInfoBean) {
//        if (!meal.MealSetlList.isNullOrEmpty()) {
//            if (meal.MealSetlList.size == 1) {
//                //选择唯一餐别
//                Config.currentMealSetId = meal.MealSetlList[0].MealSetID
//                chooseFee(meal)
//            }else {
//                MealSetSelectDialog(meal.MealSetlList) {
//                    Config.currentMealId = meal.MealSetlList[it].MealSetID
//                    chooseFee(meal)
//                }.show(supportFragmentManager, "choose")//餐别选择
//            }
//        }else {
//            toast("没有套餐信息")
//        }
//    }

    fun clientReqInStation() {
        //
    }

    private var exitTimes = 0L
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode === KeyEvent.KEYCODE_BACK) {
            // 判断两次点击的时间间隔（默认设置为2秒）
            if (System.currentTimeMillis() - exitTimes > 2000) { // 2S内则退出程序
                toast("再按一次退出")
                exitTimes = System.currentTimeMillis()
                return true
            } else {
                exitTimes = 0
                exitProcess(0)
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

}